package me.report.api.web.controller.admin;

import com.mongodb.gridfs.GridFSDBFile;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import me.report.api.mongodb.service.MongoService;
import me.report.api.web.util.Constant;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/report/view")
public class ReportViewController {

    @Autowired
    MongoService mongoService;

    @RequestMapping(value = {"/run/id/{reportId}"})
    public @ResponseBody
    ModelAndView runReportById(HttpServletRequest request,
            @PathVariable("reportId") String reportId) {

        Map model = new HashMap<String, Object>();
        
        model.put("reportViewUrl", Constant.URL_REPORT_VIEW + reportId);
        model.put("viewUrl", Constant.URL_REPORT_VIEW);
        model.put("report", mongoService.getAll());
        
        return new ModelAndView("report/view/run", model);
    }

    @RequestMapping(value = {"/file/id/{reportId}"})
    public @ResponseBody
    void fileId(HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable("reportId") String reportId) {

        // lay file tu reportIdFile
        GridFSDBFile file = mongoService.getReportFileByReportId(reportId);

        if (file != null) {
            try {
                byte[] data = IOUtils.toByteArray(file.getInputStream());
                response.setContentType(file.getContentType());
                response.setContentLength((int) file.getLength());
                response.getOutputStream().write(data);
                response.getOutputStream().flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else {
            response.setStatus(HttpStatus.NOT_FOUND.value());
        }
    }
}
